package com.andatsoft.laisim.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.adapter.LibraryAllSongsAdapter;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.entity.Song;
import com.andatsoft.laisim.service.PlayerService;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Animator;
import com.andatsoft.laisim.utils.Common;

public class SearchActivity extends BaseActivity {

	private EditText mEtSearch;
	private ListView mListViewResult;
	private LinearLayout mLayoutToolbox;
	private TextSwitcher mTsSongFoundNumber;
	private CheckBox mChkRemember;

	private DataBaseAccess mDatabase;
	private List<Song> mResultSongList;
	private LibraryAllSongsAdapter mAdapter;
	private int mSongIdSelected;
	private int mPlayType = -1; // 0: play all, 1: play filtered list
	private boolean mIsRemember;
	private int mIndex = -1;

	// Player service
	private PlayerService mPlayerService;
	private boolean mIsBoundService;

	private ServiceConnection mPlayerServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mPlayerService = null;
			Log.d("SerConnect", "Disconnect");
		}

		// called when bind service called.
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPlayerService = ((PlayerService.LocalBinder) service).getService();

		}
	};
	private boolean mIsToolBoxShowing;

	public void doBindService() {
		bindService(new Intent(SearchActivity.this, PlayerService.class),
				mPlayerServiceConnection, Context.BIND_AUTO_CREATE);
		// Log.d("Bind", "bind" + bo);
		mIsBoundService = true;
	}

	public void doUnBindService() {
		unbindService(mPlayerServiceConnection);
		mIsBoundService = false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		doBindService();
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		mResultSongList = new ArrayList<Song>();
		mAdapter = new LibraryAllSongsAdapter(getApplicationContext(),
				mResultSongList, getLayoutInflater());
		restoreSetting();
		initViews();
		setupListeners();

		mListViewResult.setAdapter(mAdapter);

	}

	private void initViews() {
		mEtSearch = (EditText) findViewById(R.id.et_search);
		mEtSearch.setBackgroundColor(getSelectedTheme().getDialogTextColor());
		mEtSearch
				.setTextColor(getSelectedTheme().getDialogBackgroundColor() | 0xff000000);
		mLayoutToolbox = (LinearLayout) findViewById(R.id.layout_tool_box_search);
		mListViewResult = (ListView) findViewById(R.id.list_view_search);
		mTsSongFoundNumber = (TextSwitcher) findViewById(R.id.text_switcher_search);
		mTsSongFoundNumber.setFactory(new ViewFactory() {

			@Override
			public View makeView() {
				TextView tv = new TextView(getApplicationContext());
				tv.setTextColor(ThemeManager.getSelectedTheme()
						.getNormalTextColor());
				tv.setTextSize(15f);
				tv.setSingleLine(true);
				tv.setEllipsize(TruncateAt.MARQUEE);
				FrameLayout.LayoutParams pa = new FrameLayout.LayoutParams(
						FrameLayout.LayoutParams.MATCH_PARENT,
						FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
				tv.setLayoutParams(pa);
				return tv;
			}
		});
		mTsSongFoundNumber.setInAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.fade_in_fast));
		mTsSongFoundNumber.setOutAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.fade_out_fast));
	}

	private void setupListeners() {
		mEtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// Log.e("key work", mEtSearch.getText().toString());
				String keyWork = mEtSearch.getText().toString();
				if (keyWork != null) {
					if (keyWork.equals("")) {
						mTsSongFoundNumber.setVisibility(View.INVISIBLE);
						mResultSongList.clear();
					} else {
						mTsSongFoundNumber.setVisibility(View.VISIBLE);
						mResultSongList.clear();
						mResultSongList.addAll(mDatabase.getAllSongByRawQuery(
								"where song_title like '%" + keyWork + "%'",
								" or song_album like '%" + keyWork + "%'"
										+ " or song_artist like '%" + keyWork
										+ "%'", "order by song_title "));
					}
					mAdapter.notifyDataSetChanged();
					mTsSongFoundNumber
							.setText(getString(R.string.lib_text_total_found)
									+ " " + mResultSongList.size());
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		mListViewResult.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				mIndex = pos;
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(mEtSearch.getWindowToken(), 0);
				mSongIdSelected = mResultSongList.get(pos).getId();
				if (mIsRemember) {
					if (mPlayType == 0) {
						// all
						doWhenPlayAllSelected();
					} else if (mPlayType == 1) {
						// filter
						doWhenPlayFilteredSelected();
					}
				} else {
					showToolbox();
				}
			}
		});
		mListViewResult
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, int pos, long arg3) {
						mIndex = pos;
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(mEtSearch.getWindowToken(),
								0);
						mSongIdSelected = mResultSongList.get(pos).getId();
						showToolbox();
						return true;
					}
				});
	}

	private void restoreSetting() {
		SharedPreferences sP = getSharedPreferences(
				Common.SP_SEARCH_SETTING_NAME, Context.MODE_PRIVATE);
		mIsRemember = sP.getBoolean(Common.SP_SEARCH_IS_REMEMBER, false);
		mPlayType = sP.getInt(Common.SP_SEARCH_PLAY_TYPE, -1);
	}

	private void closeToolbox() {
		Animator.applyAlphaAnimation(mLayoutToolbox, 500, mAnimatorEventEx,
				getSelectedTheme().getTransitionAlpha(), 0.0f);

	}

	private com.nineoldandroids.animation.Animator.AnimatorListener mAnimatorEventEx = new com.nineoldandroids.animation.Animator.AnimatorListener() {

		@Override
		public void onAnimationStart(com.nineoldandroids.animation.Animator arg0) {

		}

		@Override
		public void onAnimationRepeat(
				com.nineoldandroids.animation.Animator arg0) {

		}

		@Override
		public void onAnimationEnd(com.nineoldandroids.animation.Animator arg0) {
			unbindDrawables(mLayoutToolbox);
			mLayoutToolbox.setVisibility(View.GONE);
		}

		@Override
		public void onAnimationCancel(
				com.nineoldandroids.animation.Animator arg0) {

		}
	};

	private void showToolbox() {
		mIsToolBoxShowing = true;
		mLayoutToolbox.removeAllViews();
		getLayoutInflater().inflate(R.layout.tool_box_search, mLayoutToolbox,
				true);
		mLayoutToolbox.setVisibility(View.VISIBLE);
		// if (Utils.androidOs > Common.ANDROID_OS_GINGERBREAD) {
		Animator.applyAlphaAnimation(mLayoutToolbox, 150, null, 0.0f,
				ThemeManager.getSelectedTheme().getTransitionAlpha());
		// }

		mChkRemember = (CheckBox) findViewById(R.id.chk_box_tool_box_search_remember);
		mChkRemember.setChecked(mIsRemember);

		TextView btnPlayAll = (TextView) findViewById(R.id.tv_tool_box_search_play_all);
		btnPlayAll.setTextColor(ThemeManager.getSelectedTheme()
				.getNormalTextColor());
		setBackgroundColorForView(btnPlayAll);
		btnPlayAll.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doWhenPlayAllSelected();
					closeToolbox();
					mIsToolBoxShowing = false;
					break;
				}
				return true;
			}
		});

		TextView btnPlayResult = (TextView) findViewById(R.id.tv_tool_box_search_play_result);
		btnPlayResult.setTextColor(ThemeManager.getSelectedTheme()
				.getNormalTextColor());
		setBackgroundColorForView(btnPlayResult);
		btnPlayResult.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doWhenPlayFilteredSelected();
					// unbindDrawables(mLayoutToolbox);
					// mLayoutToolbox.setVisibility(View.GONE);
					closeToolbox();
					mIsToolBoxShowing = false;
					break;
				}
				return true;
			}
		});

		mLayoutToolbox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// unbindDrawables(mLayoutToolbox);
				// mLayoutToolbox.setVisibility(View.GONE);
				closeToolbox();
				mIsToolBoxShowing = false;
			}
		});

	}

	private void doWhenPlayAllSelected() {
		if (mPlayerService != null) {
			List<Song> allS = mDatabase.getAllSong();
			mPlayerService.setPlaylist(allS);
			mPlayerService.notifyPlaylistChanged();
			mPlayerService.playBySongId(mSongIdSelected);
			mPlayType = 0;// play all
			new SavePlaylistTask().execute(0);
			mAdapter.setSelectedItem(mIndex);
			mAdapter.notifyDataSetChanged();
		}
	}

	private void doWhenPlayFilteredSelected() {
		if (mPlayerService != null) {
			mPlayerService.setPlaylist(mResultSongList);
			mPlayerService.notifyPlaylistChanged();
			mPlayerService.playBySongId(mSongIdSelected);
			mPlayType = 1;// play filtered
			new SavePlaylistTask().execute(1);
			mAdapter.setSelectedItem(mIndex);
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!mIsBoundService)
			doBindService();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mIsBoundService)
			doUnBindService();
	}

	@Override
	public void onBackPressed() {
		if (mIsToolBoxShowing) {
			closeToolbox();
		} else {
			super.onBackPressed();
			overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
		}
	}

	private class SavePlaylistTask extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			int cmd = params[0];
			DataBaseAccess db = DataBaseAccess
					.getInstance(getApplicationContext());
			// All song
			if (cmd == 0) {
				List<Song> allS = db.getAllSong();
				db.savePlayingSong(allS);
			} else {
				// song filtered
				db.savePlayingSong(mResultSongList);
			}
			// update library index
			SharedPreferences sP = getSharedPreferences(Common.SP_LIBRARY_NAME,
					Context.MODE_PRIVATE);
			SharedPreferences.Editor ed = sP.edit();
			ed.putInt(Common.SP_LIBRARY_PLAYING_LIB_INDEX, -1);
			ed.commit();

			if (mChkRemember != null) {
				// update remember setting
				mIsRemember = mChkRemember.isChecked();
				sP = getSharedPreferences(Common.SP_SEARCH_SETTING_NAME,
						Context.MODE_PRIVATE);
				ed = sP.edit();
				ed.putBoolean(Common.SP_SEARCH_IS_REMEMBER,
						mChkRemember.isChecked());
				ed.putInt(Common.SP_SEARCH_PLAY_TYPE, mPlayType);
				ed.commit();
			}
			return null;
		}
	}

}
